package org.ttitfly.workflow.engine.mode;

import java.util.ArrayList;
import java.util.List;

import org.ttitfly.workflow.engine.Process;
import org.ttitfly.workflow.engine.Transition;
import org.ttitfly.workflow.engine.VirtualRunUnit;
import org.ttitfly.workflow.exception.ProcessRunException;


/**
 * 鉴别器，通过条件判断的就能被运行
 * 
 * @author 潘海春
 * @version 2009-9-10
 */
public class Discriminator extends VirtualRunUnit {

	/**
	 * 目标
	 */
	private String[] toUnits;

	/**
	 * 所有待鉴别的转向
	 */
	private List<Transition> transitions = new ArrayList<Transition>();

	/**
	 * 构造函数
	 * 
	 * @param parent
	 * @param name
	 * @param transitions
	 */
	public Discriminator(Process parent, String name, List<Transition> transitions) {
		this(parent, name, transitions, null);
	}

	/**
	 * 构造函数
	 * 
	 * @param parent
	 * @param name
	 * @param transitions
	 * @param toUnits
	 */
	public Discriminator(Process parent, String name, List<Transition> transitions, String[] toUnits) {
		super(parent, name);
		if (transitions == null || transitions.isEmpty()) {
			throw new IllegalArgumentException("参数[transitions]不能为空！");
		}
		this.transitions = transitions;
		this.toUnits = toUnits;
	}

	@Override
	public void run() throws ProcessRunException {
		boolean dispatched = false;
		for (Transition transition : transitions) {
			if (transition.isEffective()) {
				parent.dispatch(transition.getTarget());
				dispatched = true;
			}
		}
		if (toUnits != null && toUnits.length > 0) {
			for (String to : toUnits) {
				parent.dispatch(to);
			}
			dispatched = true;
		}
		if (!dispatched) {
			parent.checkComplete();
		}
	}
}
